package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ghost4j.util.ImageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 自媒体文章自动审核
     *
     * @param id
     */
    @Override
//    @GlobalTransactional
//    @Async("taskExecutor")  //标明这是一个异步的方法
    public void autoScanWmNews(Integer id) {

        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (null == wmNews) {
            throw new RuntimeException("自媒体文章不存在");
        }

        //2.判断文章是否是（待审核状态==1）
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            //准备纯文本内容和图片列表
            Map<String, Object> textAndImg = handleTextAndImg(wmNews);

            //自管理敏感词审核
            boolean isSensitive = handleSensitive((String) textAndImg.get("content"), wmNews);
            if (!isSensitive) return;

            //3.调用阿里云-文本审核
            boolean isTextScan = handleTextScan((String) textAndImg.get("content"), wmNews);
            if (!isTextScan) return;

            //4.调用阿里云-图片审核
            boolean isImgScan = handleImgScan((List<String>) textAndImg.get("images"), wmNews);
            if (!isImgScan) return;

            //5.调用文章微服务，保存app端相关文章
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(responseResult == null || !responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端文章失败");
            }

            //抛异常  tcc
//            int a = 1 / 0;

            //6.修改自媒体文章状态及回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(), "文章审核成功");

            //发送消息，生成article端详情页面，发送的内容，是谁？article_id
            Map<String,Object> map = new HashMap<>();
            map.put("article_id",wmNews.getArticleId());

            kafkaTemplate.send(ArticleConstants.CREATE_STATIC_URL_TOPIC,JSON.toJSONString(map));
        }


    }

    /**
     * 自管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {

        //查数据库，找到所有的敏感词
        //select sensitives from wm_sensitive
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveStrList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveStrList);

        //匹配文章内容是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content + "_" + wmNews.getTitle());
        if(map.size() > 0){
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文章中包含敏感词，敏感词"+map);
            return false;
        }
        return true;
    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端相关文章
     *
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews, dto);
        //布局
        dto.setLayout(wmNews.getType());

        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorId(wmUser.getId().longValue());
            dto.setAuthorName(wmUser.getName());
        }

        //文章的id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        //创建时间
        dto.setCreatedTime(new Date());

        return articleClient.savaAppArticle(dto);
    }

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 图片审核
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImgScan(List<String> images, WmNews wmNews) {
        boolean flag = true;

        if (images == null || images.size() == 0) {
            return flag;
        }


        try {
            //下载图片
            List<byte[]> imageList = new ArrayList<>();

            //去重
            images = images.stream().distinct().collect(Collectors.toList());

            for (String url : images) {
                byte[] bytes = fileStorageService.downLoadFile(url);

                InputStream inputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);

                //识别图片中的文字
                String result = tess4jClient.doOCR(bufferedImage);
                boolean isSensitive = handleSensitive(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }


                imageList.add(bytes);
            }

            //审核图片
            Map map = greenImageScan.imageScan(imageList);
            //审核失败
            if (map.get("suggestion").equals("block")) {
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中存在违规内容");
                flag = false;
            }

            //人工审核
            if (map.get("suggestion").equals("review")) {
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中存在不确定内容");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;

        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 纯文本审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content + "_" + wmNews.getTitle());
            //审核失败
            if (map.get("suggestion").equals("block")) {
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中存在违规内容");
                flag = false;
            }

            //人工审核
            if (map.get("suggestion").equals("review")) {
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中存在不确定内容");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;

        }
        return flag;
    }

    /**
     * 修改自媒体文章
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 准备纯文本内容和图片列表
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImg(WmNews wmNews) {

        Map<String, Object> resultMap = new HashMap<>();

        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        //文本内容
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            //纯文本
            if (map.get("type").equals("text")) {
                stringBuilder.append(map.get("value"));
            }

            //图片
            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }


        //图片内容-封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", images);

        return resultMap;

    }

    /**
     * 人工审核通过
     * @param wmNews
     * @return
     */
    public WmNews authPass(WmNews wmNews){
        //远程调用，获取返回值
        ResponseResult responseResult = saveAppArticle(wmNews);
        //校验数据
        if(responseResult == null || !responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端文章失败");
        }
        //设置app端id
        wmNews.setArticleId((Long) responseResult.getData());
        //发送消息，生成article端详情页面，发送的内容，是谁？article_id
        Map<String,Object> map = new HashMap<>();
        map.put("article_id",wmNews.getArticleId());
        kafkaTemplate.send(ArticleConstants.CREATE_STATIC_URL_TOPIC,JSON.toJSONString(map));
        return wmNews;
    }
}
